<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class CateController extends Controller
{
    //商品分类
    public function getAdd()
    {
         //查询cate表,获取所有内容
        $cate = DB::table('cates')->get();
        // dd($cate);
        return view('admin.cate.add',['cate'=>$cate]);
    }

    //执行添加分类
    public function postInsert(Request $request)
    {
        //检测
        $this->validate($request,[
            'name'=>'unique:cates,name'       //unique唯一
            ],[
            'name.unique'=>'分类名称已经存在'
            ]);
        //去除_token
        $date = $request->except(['_token']);
        // dd($date);
        if($date['pid']=='0'){
            $date['path']='0';
        }else{
            //如果不是顶级域名
            //读取父级分类信息
            $p = DB::table('cates')->where('id',$date['pid'])->first();
             //拼接path路径
            $date['path'] = $p->path.','.$p->id;
         }   
        // 添加到数据库
        $res = DB::table('cates')->insert($date);
        if($res){
            return redirect('/cate/add')->with('info','添加成功');
       }
    }

    //分类列表
    public function getIndex(Request $request)
    {
        $cate = DB::table('cates')->get();
        return view('admin.cate.index',['cate'=>$cate,'request'=>$request]);
    }

}
